from django.shortcuts import render
from rest_framework.views import APIView
from django.shortcuts import  HttpResponse
from rest_framework.viewsets import GenericViewSet


import auth01.models as models
from auth01.auth import Authentication
import time
import hashlib
from django.http import JsonResponse

# # Create your views here.
# class UserApiView(APIView):            #视图
#     def get(self,request,*args,**kwargs):
#         return HttpResponse("get")
#
# #GenericViewSet
#
# class UserApiViewSet(GenericViewSet):
#     def get(self,request,*args,**kwargs):
#         return HttpResponse("UserApiViewSet.get")




def md5(user):
    ctime=str(time.time())
    m=hashlib.md5(bytes(user,encoding="utf-8"))
    m.update(bytes(ctime,encoding="utf-8"))
    return m.hexdigest()


class AuthView(APIView):

    def dispatch(self,request,*args,**kwargs):
        return super(AuthView,self).dispatch(request,*args,**kwargs)

    def get(self,request,*args,**kwargs):
        return HttpResponse('get')

    def post(self,request,*args,**kwargs):
        ret={'code':1000,'msg':"登录成功"}
        try:
            user=request._request.POST.get("user_name")
            pwd=request._request.POST.get("password")
            print(user)
            print(pwd)
            obj=models.UserInfo.objects.filter(user_name=user,password=pwd).first()
            # print(models.UserInfo.objects.count())
            if not obj:
                ret["code"]=1001
                ret["msg"]="用户或密码错误"
            else:
                token=md5(user)
                models.UserToken.objects.update_or_create(user=obj,defaults={"token":token})
                ret["token"]=token

        except Exception as e:
            ret["code"]=1002
            ret["msg"]="请求失败"
            print(e)

        return JsonResponse(ret)

class OrderView(APIView):

    authentication_classes = [Authentication]

    def get(self,request,*args,**kwargs):
        ret = {'code': 1000, 'msg': "你的订单已经完成", 'data': "买了一个笔记本电脑"}
        return JsonResponse(ret, safe=True)